package com.qf.fmcommodity.user.controller;

import cn.hutool.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.fmcommodity.user.entity.Users;
import com.qf.fmcommodity.user.service.IUsersService;
import com.qf.fmcommodity.user.utils.Constants;
import com.qf.fmcommodity.user.vo.LoginVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 * <p>
 * 用户  前端控制器
 * </p>
 *
 * @author 苇名一心
 * @since 2023-02-13
 */
@RestController
@RequestMapping("/user")
@CrossOrigin  //允许跨域访问
public class UsersController {

    @Autowired
    IUsersService iUsersService;

    /**
     * 登入接口
     * @param username
     * @param password
     * @return
     */
    @GetMapping("/login")
    public LoginVo login(String username,String password) throws JsonProcessingException, UnsupportedEncodingException {

        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        subject.login(token);
        //获取用户信息
        Users user = (Users) subject.getPrincipal();

        //创建jwt token，并且把需要保存的数据放到token中
        //User对象 ---> json 字符串
        ObjectMapper objectMapper = new ObjectMapper();

        String userJson = objectMapper.writeValueAsString(user);

        String token1 = JWT.create().setPayload("sub", userJson)
                .setExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 14)) //token有效期 两周
                .setIssuer("fmall") //token是由谁签发的
                .setKey(Constants.SECRET.getBytes("utf-8"))
                .sign();

        LoginVo vo = new LoginVo();
        vo.put("code",10000);
        vo.put("msg",token1);
        vo.put("data",user);
        return vo;
    }

    @PostMapping("/regist")
    public LoginVo regist(@RequestBody Users users){

        iUsersService.regist(users);

        LoginVo vo = new LoginVo();
        vo.put("code",10000);

        return vo;


    }



}
